from alibabacloud_docmind_api20220711.client import Client as docmind_api20220711Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_docmind_api20220711 import models as docmind_api20220711_models
from alibabacloud_tea_util.client import Client as UtilClient
from alibabacloud_tea_util import models as util_models
from alibabacloud_credentials.client import Client as CredClient
import json
import pandas as pd
import time

def submit_file(file_path,file_type):
    cred=CredClient()
    config = open_api_models.Config(
        # 通过credentials获取配置中的AccessKey ID
        access_key_id=cred.get_access_key_id(),
        # 通过credentials获取配置中的AccessKey Secret
        access_key_secret=cred.get_access_key_secret()
    )
    # 访问的域名
    config.endpoint = f'docmind-api.cn-hangzhou.aliyuncs.com'
    client = docmind_api20220711Client(config)
    request = docmind_api20220711_models.SubmitTableUnderstandingJobAdvanceRequest(
        # file_url_object : 本地文件流
        file_url_object=open(file_path, "rb"),
        # file_name ：文件名称。名称必须包含文件类型
        # file_name='123.pdf',
        # file_name_extension : 文件后缀格式。与文件名二选一
        file_name_extension=file_type
    )
    runtime = util_models.RuntimeOptions()
    try:
        # 复制代码运行请自行打印 API 的返回值
        response = client.submit_table_understanding_job_advance(request, runtime)
        # API返回值格式层级为 body -> data -> 具体属性。可根据业务需要打印相应的结果。如下示例为打印返回的业务id格式
        # 获取属性值均以小写开头，
        return str(response.body.data.id)
    except Exception as error:
        # 如有需要，请打印 error
        UtilClient.assert_as_string(error.message)


def query(ID):
    cred=CredClient()
    config = open_api_models.Config(
        # 通过credentials获取配置中的AccessKey ID
        access_key_id=cred.get_access_key_id(),
        # 通过credentials获取配置中的AccessKey Secret
        access_key_secret=cred.get_access_key_secret()
    )
    # 访问的域名
    config.endpoint = f'docmind-api.cn-hangzhou.aliyuncs.com'
    client = docmind_api20220711Client(config)
    request = docmind_api20220711_models.GetTableUnderstandingResultRequest(
        # id :  任务提交接口返回的id
        id=ID
    )
    try:
        # 复制代码运行请自行打印 API 的返回值
        response = client.get_table_understanding_result(request)
        # API返回值格式层级为 body -> data -> 具体属性。可根据业务需要打印相应的结果。获取属性值均以小写开头
        # 获取异步任务处理情况,可根据response.body.completed判断是否需要继续轮询结果
        print(response.body.completed, end = '\n')
        # 获取返回结果。建议先把response.body.data转成json，然后再从json里面取具体需要的值。
        return response.body.completed,response.body.data
        # print(json.dumps(response.body.data))
    except Exception as error:
        # 如有需要，请打印 error
        UtilClient.assert_as_string(error.message)

def table_to_html(table_dict):
    table_html=''
    for i in table_dict['tables']:
        table_html += "<table><caption>"+i['tableName']+"</caption><tr>"
        zhizhen=-1
        #添加表头
        for item in i['cells']:
            if item['colNumber']>zhizhen:
                table_html += f"<th>{item['content']}</th>"
                zhizhen=item['colNumber']
            else:
                table_html += "</tr>"
        # 添加表格内容
        for row in i['cells'][zhizhen+1:]:
            if row['colNumber']==0:
                table_html+='<tr>'
            table_html += f"<td>{row['content']}</td>"
            if row['colNumber']==zhizhen:
                table_html += "</tr>"
            zhizhen = row['colNumber']
        table_html += "</table>"
    return table_html

if __name__=='__main__':
    file_path='test.png'
    file_save='test.html'
    file_type='png'
    ID=submit_file(file_path,file_type)
    while ID:
        completed,json_str=query(ID)
        if completed:
            print(json_str)
            # 打开一个文本文件，并将Python对象以文本形式写入
            with open(file_save, "w", encoding = 'utf-8') as file:
                file.write(table_to_html(json_str))
            break
        time.sleep(1)
